<!-- 权限列表展示 -->
<template>
  <el-card class="box-card">
    <el-table
      :data="primissions"
      style="width: 100%; margin-bottom: 1.25rem"
      row-key="id"
      border
      :expand-row-keys="expands"
      @expand-change="toggleRowExpansion"
    >
      <el-table-column prop="name" label="权限名称" width="200" />
      <el-table-column prop="icon_cls" label="权限图标" width="200" />
      <el-table-column prop="remark" label="权限编码" width="220" />
      <el-table-column prop="path" label="组件路径编码" width="180" />
      <el-table-column prop="description" label="组件路径编码" width="180" />
      <el-table-column prop="createdAt" label="创建时间" width="200" />
      <!-- 天剑修改按钮组 -->
      <el-table-column label="操作" fixed="right" width="260">
        <template #default="scope">
          <el-button
            class="el-button--text"
            v-permission="['202001']"
            size="small"
            type="primary"
            plain
            icon="Plus"
            @click="add(scope.row)"
          >增加</el-button>
          <el-button
            type="success"
            class="el-button--text"
            plain
            v-permission="['202002']"
            icon="edit"
            size="small"
            @click="edit(scope.row)"
          >修改</el-button>
          <el-button
            type="danger"
            size="small"
            class="el-button--text"
            plain
            v-permission="['202003']"
            icon="Delete"
            @click="del(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 添加修改弹出框 -->

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" draggable>
    <!-- from 提交表单 -->

    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <!-- 上级菜单 -->
      <el-form-item label="上级菜单" v-show="!ruleForm.id && ruleForm.grade!=0" prop="pid">
        <treeselect v-model="selected" :multiple="false" :options="options" @select="selectNode" />
      </el-form-item>
      <!-- 菜单类型 -->
      <el-form-item label="菜单类型" prop="grade" v-show="!ruleForm.id">
        <el-radio-group v-model="ruleForm.grade" @change="selectType">
          <el-radio :label="0">目录</el-radio>
          <el-radio :label="1">菜单</el-radio>
          <el-radio :label="2">按钮</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 菜单图标 -->
      <el-form-item label="图标名称" v-show="ruleForm.grade!=2">
        <el-input v-model="ruleForm.icon_cls" width="40px" placeholder="请输入菜单图标名称"></el-input>
      </el-form-item>
      <!-- 菜单名称 -->
      <el-form-item label="菜单名称">
        <el-input v-model="ruleForm.name" placeholder="请输入菜单名称"></el-input>
      </el-form-item>

      <div v-show="ruleForm.grade!=2">
        <!-- 菜单路径 -->
        <el-form-item label="菜单路径">
          <el-input v-model="ruleForm.path" placeholder="请输入菜单路径(完整路径如:/home/SysUser,目录默认为'/')"></el-input>
        </el-form-item>
        <!--  菜单组件名称-->
        <el-form-item   v-show="ruleForm.grade==1"  label="菜单组件名称" >
       
       
      <el-input v-model="ruleForm.component" placeholder="请输入菜单组件名称如:SysUser"></el-input>
         
        </el-form-item>
        <!--  菜单描述-->
        <el-form-item label="菜单描述">
          <el-input v-model="ruleForm.description" placeholder="请输入菜单描述"></el-input>
        </el-form-item>
      </div>
      <!--  菜单标识-->
      <el-form-item label="菜单标识" v-show="!ruleForm.id">
        <el-input v-model.number="ruleForm.remark" placeholder="请输入菜单菜单标识数字"></el-input>
      </el-form-item>
      <!-- 菜单菜单显示 -->
      <el-form-item label="是否隐藏" v-show="ruleForm.grade==2">
        <el-radio-group v-model="ruleForm.enabled" @change="selectShow">
          <el-radio :label="true">显示</el-radio>
          <el-radio :label="false">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">Submit</el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { Treeselect } from 'vue3-treeselect'
import { useStore } from 'vuex'
import { reactive, ref, onMounted, toRef, toRefs } from 'vue'
import { tree } from '@/utils/tree.js'
import { getMenulists } from '@/api/menu.js'
import { UpdateMenu, addMenu, delMenu } from '@/api/menu'
import { ElMessage } from 'element-plus'
import { getRemarks } from '@/api/user'
const store = new useStore()
const primissions = ref([])
// 转成树形结构
const getdata = async () => {
  const { data } = await getMenulists()
  primissions.value = tree(data)
}
getdata()

// primissions.value = tree(store.getters.routers)
const currentId = ref()
// 默认展开行
const expands = ref(['2', '5'])
// 弹框的标题
const dialogTitle = ref('修改菜单')
// 是否显示
let dialogVisible = ref(false)
// 表单实例对象
const ruleFormRef = ref()
// 表单对象
let ruleForm = reactive({
  id: undefined,
  icon_cls: '', // 图标
  grade: 2, // 分类 （0目录,1菜单,2按钮）
  name: '', // 名称
  path: '', // 路径 全路径
  component: '', // 组件名称
  enabled: true, // 是否隐藏 不显示在左侧菜单
  remark: '', // 唯一标识
  orders: '', // 父级的id
  description: '', // 藐视
  pid: undefined, // 父id
   
  
})

let options = ref([])
// 处理options
const formateOptions = async () => {
  const { data } = await getMenulists()
  if (Array.isArray(data)) {
    data.forEach((item) => {
      item.label = item.name
    })
  }
  // 递归c去除children属性
  function diGuiTree(res) {
    res.forEach((item) => {
      item.children === '' ||
      item.children === undefined ||
      item.children === null ||
      item.children.length == 0
        ? delete item.children
        : diGuiTree(item.children)
    })

    return res
  }

  options.value = diGuiTree(tree(data))
}

let selected = ref(null)
let obj = ref(null)
formateOptions()
// 添加属性菜单监听选中的值
const selectNode = (val) => {
  selected.value = val
  obj.value = val
}
// 单选按钮
const selectType = (val) => {
  ruleForm.grade = val
}
// 单选框显示于隐藏
const selectShow = (val) => {
  ruleForm.enabled = val
}

const toggleRowExpansion = (row, expandedRows) => {
  // 点击先清空数组 全部合起来
  expands.value = []
  // 点击之前 expandedRows 分为 true / false
  if (expandedRows) {
    // ture 代表之前是合起状态 现在要展开起来
    // 找到父节点一起放进数组
    expands.value.push(String(row.id))
    expands.value.push(String(row.pid))
  } else {
    // false 代表要合起来，
    //如果是根节点pid不在列表所以无效
    // 如果是叶子节点 把pid 放进数组 代表只合起自己
    expands.value.push(String(row.pid))
  }
}

// 修改
const edit = (val) => {
  dialogTitle.value = '修改菜单'
  currentId.value = val.id
  dialogVisible.value = true
  for (const key in ruleForm) {
    ruleForm[key] = val[key]
  }
  selected.value = val.name
}
// 添加
const add = (val) => {
  currentId.value = val.id
  dialogTitle.value = '添加菜单'

  // 清空所有的数据
  for (const key in ruleForm) {
    ruleForm[key] = ''
  }
  // 默认显示全部的配置项
  ruleForm.grade = 1
  ruleForm.enabled = true
  dialogVisible.value = true
}
//删除
const del = async (val) => {
  currentId.value = val.id
  const data = await delMenu({ ids: val.id })
  if (data.code == 200) {
    ElMessage.success(data.msg)
    getdata()
  }
}
// 弹框关闭回调
const resetForm = (ruleFormRef) => {
  dialogVisible.value = false
  // 清空数据
  for (const key in ruleForm) {
    ruleForm[key] = ''
  }
  // 默认显示全部的配置项
  ruleForm.grade = 0
  ruleForm.enabled = true
}
// 弹框确定回调
const submitForm = (ruleFormRef) => {
 
  ruleFormRef.validate(async (valid) => {
    if (!valid) return
    let data
    if (ruleForm.id) {
      // 修改
      const res = await UpdateMenu({
        id: currentId.value,
        name: ruleForm.name,
        icon_cls: ruleForm.icon_cls,
        path: ruleForm.path,
        grade: ruleForm.grade,
        enabled:ruleForm.enabled,
        description: ruleForm.description,
        remark: ruleForm.remark,
        
      })
      data = res
    } else {
      // 添加
      // 0目录   父级的pid菜单    null按钮
      // ruleForm.pid
      // 0目录   父级的pid菜单    父id按钮
      // ruleForm.orders

      if (ruleForm.grade == 0) {
        // 目录
        ruleForm.orders = 0
        ruleForm.pid = 0
      } else if (ruleForm.grade == 1) {
        // 菜单
        ruleForm.orders = obj.value.id
        ruleForm.pid = obj.value.id
      } else {
        // 按钮
        ruleForm.orders = obj.value.id
        ruleForm.pid = null
      }

      const req = await addMenu({
        name: ruleForm.name,
        path: ruleForm.path,
        description: ruleForm.description,
        remark: ruleForm.remark,
        grade: ruleForm.grade,
        component: ruleForm.component,
        enabled: ruleForm.enabled,
        orders: ruleForm.orders,
        pid: ruleForm.pid,
      })
      data = req
    }
    if (data.code == 200) {
      ElMessage.success(data.msg)
      // 重新回去 权限列表
       const { data: remarks } = await getRemarks()
       store.commit('user/setRemarks', remarks)
      getdata()
       dialogVisible.value = false

    }
  })
}
</script>
<style lang='less' scoped>
::v-deep .el-input .el-input--default .el-input--suffix {
  width: 80% !important;
}
 
</style>